
import styles from './index.module.less'
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'

export default function AIxiaoxi() {
  const [question, setQuestion] = useState('')
  const [content, setContent] = useState('')
  const [streaming, setStreaming] = useState(false)
  const navigate = useNavigate()
  const back = () => {
    navigate('/petClass')
  }
  let str = ''


  const update = async () => {
  if (!question) return
  setContent('思考中...')
  
  const endpoint = 'https://api.deepseek.com/chat/completions'
  const headers = {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${import.meta.env.VITE_DEEPSEEK_API_KEY}`
  }
  const response = await fetch(endpoint, {
    method: 'POST',
    headers: headers,
    body: JSON.stringify({
      model: 'deepseek-chat',
      messages: [{role: 'user', content: question}],
      stream: streaming
    })
  })

  if (streaming) {
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let done = false
    let buffer = ''
    let isFirstChunk = true // 添加标志位

    while (!done) {
      const { value, done: readerDone } = await reader.read()
      done = readerDone
      const chunkValue = buffer + decoder.decode(value)
      buffer = ''
      const lines = chunkValue.split('\n').filter(line => line.startsWith('data: '))
      
      for (const line of lines) {
        const incoming = line.slice(6)
        if (incoming === '[DONE]') {
          done = true
          break
        }

        try {
          const data = JSON.parse(incoming)
          const delta = data.choices[0].delta.content
          
          if (delta) {
            if (isFirstChunk) {
              // 第一次接收到数据，清除"思考中..."
              setContent(delta)
              isFirstChunk = false
            } else {
              setContent((prev) => prev + delta)
            }
          }
        } catch(err) {
          console.log(err)
        }
      }
    }
  } else {
    const data = await response.json()
    setContent(data.choices[0].message.content)
  }
}

  return (
    <div className={styles.container}>
      <div>
        <label>请输入：</label>
        <input type="text" className={styles.input} onChange={(e) => setQuestion(e.target.value)} />
        <button onClick={update}>发送</button>
        <button onClick={back}>返回</button>
      </div>
      <div className={styles.response}>
        <div>
          <label >streaming</label>
          <input type="checkbox" onChange={(e) => {
            setStreaming(e.target.checked)
          }} />
        </div>
        <div>{content}</div>
      </div>
    </div>
  )
}
